<template>
  <div class="UploadImg">
    <el-upload class="avatar-uploader" action="" :show-file-list="false" :http-request="upload" :before-upload="beforeAvatarUpload">
      <i class="el-icon-circle-close avatar-uploader-icon" />
      <img v-if="value" :src="value" class="avatar" alt="">
      <span class="Upload" v-else>上传图片</span>
    </el-upload>

  </div>
</template>

<script>
// 下面的代码是固定写法
const COS = require('cos-js-sdk-v5')
// 填写自己腾讯云cos中的key和id (密钥)
const cos = new COS({
  SecretId: 'AKIDTjkW2HFwMWP1MPBguqWv3uUosfCTTCep', // 身份识别ID
  SecretKey: 'xe4D6i37vSiiV1GEuKTKuEH3XkgLnzva' // 身份秘钥
})
export default {
  name: 'UploadImg',
  components: {},
  props: {
    // 从父组件传递过来的v-model对应的值
    value: { type: String, default: '' }
  },
  data () {
    return {
    }
  },
  methods: {
    upload (res) {
      if (!res.file) return
      // 执行上传操作
      cos.putObject({
        Bucket: 'dahai-1306051795', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-nanjing', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: res.file.name, /* 文件名 */
        StorageClass: 'STANDARD', // 上传模式, 标准模式
        Body: res.file // 上传文件对象
        // eslint-disable-next-line space-before-function-paren
      }, async (err, data) => {
        console.log(err || data)
        // 上传成功之后
        if (data.statusCode === 200) {
          // this.value = `https://${data.Location}`
          this.$emit('input', `https://${data.Location}`)
        }
      })
    },
    beforeAvatarUpload (file) {
      const isPNG = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPNG) {
        this.$message.error('只能上传图片格式的文件!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isPNG && isLt2M // 如果这里返回的是 false 则会阻止文件上传
    }
  }
}
</script>

<style lang='scss' scoped>
.UploadImg {
  margin-left: 300px;
  margin-top: -45px;
}
::v-deep .el-upload {
  display: flex;
  position: relative;
  align-items: center;
  justify-content: center;
  border-radius: 5px;
  margin-left: 5px;
  width: 100px;
  height: 55px;
  border: 1px dashed #d9d9d9;
  i {
    position: absolute;
    width: 20px;
    font-size: 20px;
    right: -10px;
    top: -10px;
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;

  width: 178px;
  text-align: center;
}
.Upload {
  font-size: 12px;
  color: #000;
}
.avatar {
  display: block;
  width: 100px;
  height: 55px;
}
</style>
